<script setup lang="ts">
import { CheckboxValueType, ElCheckbox, ElOption, ElSelect } from 'element-plus';
import { computed, nextTick, ref, watch } from 'vue';

const props = defineProps<{
  value?: unknown[];
  selectOption?: {
    label?: string;
    value?: string;
    options: Array<any>;
  };
}>();
const emits = defineEmits<{
  (event: 'update:value', value: unknown[] | undefined): void;
  (event: 'change', value: any): void;
}>();
const checkAll = ref(false);
const selectChange = (value: any) => {
  emits('change', value);
};
const selectAll = (value: CheckboxValueType) => {
  if (value) valueComp.value = (props.selectOption?.options || []).map((item) => item[props.selectOption?.value || 'value']);
  else valueComp.value = [];
  emits('change', valueComp.value);
};
watch(
  [() => props.value, () => props.selectOption?.options],
  (val) => {
    nextTick(() => {
      if (val[0]?.length === val[1]?.length) checkAll.value = true;
      else checkAll.value = false;
    });
  },
  { immediate: true },
);
const valueComp = computed({
  get: () => {
    return props.value;
  },
  set: (val) => {
    emits('update:value', val);
  },
});
</script>

<template>
  <el-select class="select-with-all" popper-class="select-with-all-popper" @change="selectChange" v-model="valueComp" multiple>
    <template #header>
      <el-checkbox v-model="checkAll" @change="selectAll"> 全选 </el-checkbox>
    </template>
    <el-option
      v-for="e in selectOption?.options || []"
      :key="e[selectOption?.value || 'value']"
      :label="e[selectOption?.label || 'label']"
      :value="e[selectOption?.value || 'value']"
    />
  </el-select>
</template>

<style lang="scss">
.select-with-all-popper {
  .el-select-dropdown__header {
    padding: 3px 10px 3px 20px !important;
  }
}
</style>
